﻿using System;
using System.Collections;
using System.Collections.Generic;
using SystemDebug = System.Diagnostics.Debug;

using UnityEngine;


public class RecruitScene : Scene
{
    enum SCENEMODE
    {
       recruit
    }

    MemberModel m_SelectMember = null;

    SCENEMODE m_SceneMode = SCENEMODE.recruit;


    #region 애니메이션 변수
    public Animation m_InfoUIAni;           //인포 패널 등장 퇴장 애니   
    public Animation m_SortAni;  
    public Animation m_CharacterAni;        //캐릭터 중앙 오가는 애니
    public Animation m_RecruitTextAni;          //길드원 정보 텍스트 등장애니 
    #endregion


    #region 길드원 정렬 관련 변수

    public UILabel[] m_SortKindsLabel;

    bool m_IsSortMenuOn = false;
    SortKind m_SortKind = SortKind.Level;

    string tempString0 = null;
    string tempString1 = null;
    string tempString2 = null;
    #endregion

    public GameObject m_BlankRoot;

    public GameObject m_InfoScrollPanel;

    public GameObject m_LeftListOrizin;
    const float ListMemberStartY = 135.0f;
    const float ListMemberGap = 195.0f;

    List<MemberModel> m_SortedMemberList = new List<MemberModel>();

    List<Oc_MemberListItem> m_LeftListItems = new List<Oc_MemberListItem>();

    public Transform m_LightProbeAnchorRoot;

    public override void AwakeScene()
    {
        Instance = this;

		Popup_Blur.ClearAll();

        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "heeso", string.Empty, OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {
            StartCoroutine("StartSceneWithDelay");
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;

        StartCoroutine("StartSceneWithDelay");
    }


    IEnumerator StartSceneWithDelay()
    {
        yield return new WaitForSeconds(0.0f);

        //SetActiveHelpButton(true);

        tempString0 = TextController.GetStringWithId("uiCommonTextLevel");
        tempString1 = TextController.GetStringWithId("uiCommonTextRarityDo");
        tempString2 = TextController.GetStringWithId("uiCommonTextEnhance");

        //일단 레벨순으로 설정
        m_SortKindsLabel[0].text = tempString0;
        m_SortKindsLabel[1].text = tempString1;
        m_SortKindsLabel[2].text = tempString2;


        SortMember();

        CreateList();

        StartSceneAni();
    }


    void CreateList()
    {
        // 정렬메뉴 x -700 에서 씬 시작
        Vector3 pos = m_SortAni.transform.localPosition;
        pos.x = -700.0f;
        m_SortAni.transform.localPosition = pos;

        SortMember();

        // 레프트 메뉴 x -700 에서 씬 시작
        GameObject temp = null;
        Oc_MemberListItem tempML = null;

        int index = 0;

        if (m_SortedMemberList.Count > 0)
        {
            foreach (MemberModel model in m_SortedMemberList)
            {
                if (index > 0)
                    temp = Instantiate(m_LeftListOrizin) as GameObject;
                else
                    temp = m_LeftListOrizin;

                temp.transform.parent = m_LeftListOrizin.transform.parent;
                temp.transform.localScale = m_LeftListOrizin.transform.localScale;
                temp.name = string.Format("memberList_A{0}", index + 1);
                pos = m_LeftListOrizin.transform.localPosition;
                pos.x = -700.0f;
                pos.y = ListMemberStartY - (ListMemberGap * index);
                temp.transform.localPosition = pos;

                tempML = temp.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
                tempML.SetList(model);
                m_LeftListItems.Add(tempML);

                index++;
            }
        }
        else
        {
            m_LeftListOrizin.SetActive(false);
        }

        if (m_SelectMember == null && m_SortedMemberList.Count > 0)         
            m_SelectMember = m_LeftListItems[0].m_MemberModel;

        if (m_SelectMember != null)
        {
            m_SortAni.gameObject.SetActive(true);
            m_BlankRoot.SetActive(false);
            m_InfoUIAni.gameObject.SetActive(true);
            UpdateInfoUI(m_SelectMember);
        }
        else
        {
            // 정보 없다고 띄울것
            m_SortAni.gameObject.SetActive(false);
            m_InfoUIAni.gameObject.SetActive(false);
            m_BlankRoot.SetActive(true);
        }

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_LeftListItems[i].m_MemberModel == m_SelectMember)
                m_LeftListItems[i].SetOn(false);
        }
    }


    public void StartSceneAni()
    {
        //infoList 패널 올라오는 애니
        Vector3 pos = m_InfoUIAni.transform.localPosition;   //인포 패널 시작 y -1500으로 시작
        pos.y = -1500.0f;
        m_InfoUIAni.transform.localPosition = pos;
        StartCoroutine(InfoListAniDelay(0.5f));

        MemberListAni(true);

        m_RecruitTextAni.Play("3D_Text_in");
        m_RecruitTextAni.Play("3D_Text_idle", AnimationPlayMode.Queue);       
    }

    IEnumerator InfoListAniDelay(float time)        // 로딩이후 애니 끊김현상 방지 0.5초 딜레이
    {
        yield return new WaitForSeconds(time);
        m_InfoUIAni.Play("infoUI_up");

        //GoInfoMenu();
    }


    public void MemberListAni(bool isIn)
    {
        if (isIn)
        {
            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -700.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -3.0f, "time", 0.5f, "easetype", "spring"));

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", 1.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f)));
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
        else
        {
            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -3.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring"));      // 나가는 애니

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
    }

    void SetSortMenuUI(SortKind kind)
    {
        m_SortKind = kind;

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        for (int i = 1; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].SetOff();
        }

        if (m_LeftListItems.Count > 0)
        {
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
            UpdateInfoUI(m_LeftListItems[0].m_MemberModel);
            m_LeftListItems[0].SetOn(false);
        }
    }


    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = (SortKind)(((int)m_SortKind + num) % 3);   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        for (int i = 1; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].SetOff();
        }

        if (m_LeftListItems.Count > 0)
        {
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
            UpdateInfoUI(m_LeftListItems[0].m_MemberModel);
            m_LeftListItems[0].SetOn(false);
        }
    }


    void SortMember()
    {
        m_SortedMemberList.Clear();

        if (m_SceneMode == SCENEMODE.recruit)
        {
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.memStation)
            {
                m_SortedMemberList.Add(t.Value);
            }
        }

        int max = m_SortedMemberList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case SortKind.Level:
                        {
                            if (m_SortedMemberList[j].level < m_SortedMemberList[j + 1].level)
                            {
                                MemberModel temp = m_SortedMemberList[j];
                                m_SortedMemberList[j] = m_SortedMemberList[j + 1];
                                m_SortedMemberList[j + 1] = temp;
                            }                                
                        }
                        break;
                    case SortKind.Rare:
                        {
                            if (m_SortedMemberList[j].rarity < m_SortedMemberList[j + 1].rarity)
                            {
                                MemberModel temp = m_SortedMemberList[j];
                                m_SortedMemberList[j] = m_SortedMemberList[j + 1];
                                m_SortedMemberList[j + 1] = temp;
                            }   
                        }
                        break;
                    case SortKind.Inhance:
                        {
                            if (m_SortedMemberList[j].strengthening < m_SortedMemberList[j + 1].strengthening)
                            {
                                MemberModel temp = m_SortedMemberList[j];
                                m_SortedMemberList[j] = m_SortedMemberList[j + 1];
                                m_SortedMemberList[j + 1] = temp;
                            }   
                        }
                        break;
                }
            }
        }
    }


    void SetLeftListUI()
    {
        int max = 0;
        foreach (MemberModel model in m_SortedMemberList)
        {
            m_LeftListItems[max].gameObject.SetActive(true);
            m_LeftListItems[max].SetList(model);
            max++;
        }

        for(int i = max; i < m_LeftListItems.Count ; i++)
        {
            m_LeftListItems[i].gameObject.SetActive(false);
        }


        if (m_SortedMemberList.Count > 0)
        {
            m_SortAni.gameObject.SetActive(true);
            m_BlankRoot.SetActive(false);
            m_InfoUIAni.gameObject.SetActive(true);           
        }
        else
        {
            // 정보 없다고 띄울것
            m_SortAni.gameObject.SetActive(false);
            m_InfoUIAni.gameObject.SetActive(false);
            m_BlankRoot.SetActive(true);

            if(m_3DModel != null)
            {
                Destroy(m_3DModel);
            }
        }
    }

    void UpdateInfoUI(MemberModel tempModel)
    {
        //membermodel
        SetCharacterModel(tempModel);

        OC_InfoUIWithScroll.instance.UpdateInfoUI(tempModel);    
    }


    // 동적 케릭터 모델 관리
    GameObject m_3DPosition = null;
    [HideInInspector]
    public GameObject m_3DModel = null;

	void SetCharacterModel(MemberModel selectModel)
    {      
        if (m_3DPosition == null)
            m_3DPosition = GameObject.Find("LobbyVersion/Position");

        string modelName = GameData.Inst.ModelDefineDic[selectModel.model];

        if (m_3DModel != null && m_3DModel.name.Equals(modelName))  // 같은 위치 케릭터면 이전 케릭터 재사용
        {
            return;
        }
        else if (m_3DModel != null)
            Destroy(m_3DModel);

		m_3DModel = BattleResManager.CreatePawn(0, selectModel.model , false);
		SystemDebug.Assert( m_3DModel );
        m_3DModel.name = modelName;

        var root = m_3DPosition.transform;
		//string model_no = MyUtil.FindClassWithModelName(modelName);

        int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
        string model_no = modelName;
        bool isHaveUnderBar = (nRemoveIndex != -1);

        for (int j = 0; j < root.childCount; j++)
        {
            bool isCorrectRoot = false;
            if (isHaveUnderBar)
            {
                string rootName = root.GetChild(j).name.Remove(4);
                string childName = model_no.Remove(4);
                isCorrectRoot = rootName.Equals(childName);
            }
            else    // 언더바 안들은 애들은 이전 방식으로 찾는다
            {
                string rootName = root.GetChild(j).name;
                string childName = model_no;
                isCorrectRoot = rootName.Contains(childName);
            }

            if (isCorrectRoot)
            {
				m_3DModel.transform.parent = root.GetChild( j );
				m_3DModel.transform.localScale = Vector3.one;
				m_3DModel.transform.localPosition = Vector3.zero;
				m_3DModel.transform.localRotation = Quaternion.Euler( Vector3.zero );
                break;
            }
        }

	    var ani = m_3DModel.GetComponent<Animation>();
        ani["lobby01"].clip.wrapMode = WrapMode.Loop;
        ani.Play("lobby01");

        AttachAnchor();
    }

    void AttachAnchor()
    {
        SkinnedMeshRenderer[] tList = m_3DModel.GetComponentsInChildren<SkinnedMeshRenderer>();

        if (tList != null)
        {
            Transform tempAnchor = m_LightProbeAnchorRoot.Find(m_3DModel.name);

            for (int i = 0; i < tList.Length; i++)
            {
                tList[i].lightProbeAnchor = tempAnchor;
            }
        }
    }


    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        if (collider.name.Contains("memberList_A"))
        {
            Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
                       
            if (m_SelectMember != Choise_ML.m_MemberModel)      // 이전 선택 길드원과 다를때
            {
                UpdateInfoUI(Choise_ML.m_MemberModel);
                // 다른 인원 선택시 인포 리스트 초기화 
                OC_InfoUIWithScroll.instance.m_SelectListNum = -1;
                OC_InfoUIWithScroll.instance.MoveList();

                m_SelectMember = Choise_ML.m_MemberModel;
            }                    

            foreach (Oc_MemberListItem t_ML in m_LeftListItems)
            {
                if (t_ML.Equals(Choise_ML))
                    t_ML.SetOn(true);
                else
                    t_ML.SetOff();
            }
        }
        else if (collider.name.Contains("Button_Sort_"))
        {
            if (m_IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_close");
            }
            else
            {
                m_SortAni.Play("sort_open");
            }
            m_IsSortMenuOn = !m_IsSortMenuOn;
        }

        switch (collider.gameObject.name)
        {
            case "Button_Sort":
                {
                    if (m_IsSortMenuOn)
                        m_SortAni.Play("sort_close");
                    else
                        m_SortAni.Play("sort_open");

                    m_IsSortMenuOn = !m_IsSortMenuOn;
                }
                break;
            case "Button_Recruit":
                {
                    NetworkManager.Instance.C2S_GUILD_EMPLOY(m_SelectMember.no, CallBackOfEMPLOY);
                }
                break;
            case "Button_Reject":
                {
                    Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
                    popupSc.SetPopupWithTitleAndBody(string.Format("{0}{1}", TextController.GetStringWithId("uiCommonTextRecruit"), TextController.GetStringWithId("uiCommonTextCancel")), 
                        string.Format("{0} {1}", TextController.GetStringWithId(string.Format("charName{0}", m_SelectMember.name)),
                        TextController.GetStringWithId("uiPopupuiCharRecruitCaution1")));
                    popupSc.SetPopupWithYesNoString(string.Format("{0}{1}", TextController.GetStringWithId("uiCommonTextRecruit"), TextController.GetStringWithId("uiCommonTextCancel"))
                        , TextController.GetStringWithId("uiCommonTextNo"));
                    popupSc.SetEventOK(gameObject, "OnDismissPopup");
                }
                break;
            case "Button_Back":
                BackButton();
                break;
        }
    }

    void OnDismissPopup()
    {
        NetworkManager.Instance.C2S_GUILD_DISCH(m_SelectMember.no, CallBackOfDisch);
    }


    void CallBackOfEMPLOY(ResponseModel<UserModel> data)
    {
        if(data.ecode == 0)
        {
            UserData.Instance.userModel = data.data;
            SetSortMenuUI(m_SortKind);
        }
        else if (data.ecode == -3106) // 등용 실패
        {
            Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
            popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiMainCharManagement"), TextController.GetStringWithId("uiCommonTextNo"));
            popupSc.SetEventOK(gameObject, "OnEmploy3106");
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }  
    }

    void OnEmploy3106()
    {
        SceneController.LoadLevel("Character_Info");
    }

    void CallBackOfDisch(ResponseModel<UserModel> data)
    {
        if (data.ecode == 0)
        {
            UserData.Instance.userModel = data.data;
            SetSortMenuUI(m_SortKind);
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }  
    }

    public override void BackButton()
    {
        SceneController.LoadLevel("Main");       
    }
}